import type { MenuData, UserInfo } from '@/api/types/user.types'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { usePermissionStore } from './permission'
import { getToken } from '@/utils/auth'

export const useUserStore = defineStore(
  'user',
  () => {
    const token = ref<string>('')
    const userInfo = ref<UserInfo | null>(null)
    const menuList = ref<MenuData[]>([])
    const permissions = ref<string[]>([])

    /**
     * 初始化用户信息和 token 同步
     * 这个函数应该在应用启动时由根组件调用
     */
    const initialize = () => {
      const cookieToken = getToken()
      if (cookieToken && cookieToken !== token.value) {
        // 如果 Cookies 中的 token 与 localStorage 中的不一致，以 Cookies 为准
        token.value = cookieToken
      } else if (!cookieToken && token.value) {
        // 如果 Cookies 中没有 token 但 localStorage 中有，清除 localStorage 中的数据
        reset()
      }
    }

    /**
     * 设置 Token
     */
    const setToken = (newToken: string) => {
      token.value = newToken
    }

    /**
     * 设置用户信息
     */
    const setUserInfo = (info: UserInfo) => {
      userInfo.value = info
    }

    /**
     * 设置菜单列表
     */
    const setMenuList = (menus: MenuData[]) => {
      menuList.value = menus
    }

    /**
     * 设置权限列表
     */
    const setPermissions = (perms: string[]) => {
      permissions.value = perms
    }

    /**
     * 检查是否有权限
     */
    const hasPermission = (permission: string | string[]): boolean => {
      if (!permission) return true
      if (Array.isArray(permission)) {
        return permission.some((perm) => permissions.value.includes(perm))
      }
      return permissions.value.includes(permission)
    }

    /**
     * 重置用户信息
     */
    const reset = () => {
      token.value = ''
      userInfo.value = null
      menuList.value = []
      permissions.value = []
      
      // 清除路由
      const permissionStore = usePermissionStore()
      permissionStore.clearRoutes()
    }

    return {
      token,
      userInfo,
      menuList,
      permissions,
      initialize,
      setToken,
      setUserInfo,
      setMenuList,
      setPermissions,
      hasPermission,
      reset
    }
  },
  {
    persist: {
      key: 'user',
      storage: localStorage,
      pick: ['token', 'userInfo', 'menuList', 'permissions']
    }
  }
)
